package com.yaozheng.vocationaltraining.fragment.exam;

import android.content.Intent;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.widget.TextView;

import com.yaozheng.vocationaltraining.R;
import com.yaozheng.vocationaltraining.activity.HomeActivity;
import com.yaozheng.vocationaltraining.db.PaperAnswerCacheDao;
import com.yaozheng.vocationaltraining.fragment.BaseFragment;
import com.yaozheng.vocationaltraining.iview.checkpoints_trip.ICheckpointsTripQuestionView;
import com.yaozheng.vocationaltraining.iview.checkpoints_trip.ICheckpointsTripView;
import com.yaozheng.vocationaltraining.service.checkpoints_trip.CheckpointsTripQuestionService;
import com.yaozheng.vocationaltraining.service.checkpoints_trip.CheckpointsTripService;
import com.yaozheng.vocationaltraining.service.impl.checkpoints_trip.CheckpointsTripQuestionServiceImpl;
import com.yaozheng.vocationaltraining.service.impl.checkpoints_trip.CheckpointsTripServiceImpl;
import com.yaozheng.vocationaltraining.utils.Constants;
import com.yaozheng.vocationaltraining.utils.JsonUtils;
import com.yaozheng.vocationaltraining.utils.TypeUtils;
import com.yaozheng.vocationaltraining.view.checkpointsTrip.ItemCheckpointsTripView;

import net.sf.json.JSONObject;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;

import java.util.List;

/**
 * 闯关之旅
 *
 * @author Administrator
 */
@EFragment(R.layout.activity_checkpoints_trip)
public class CheckpointsTripFragment extends BaseFragment implements
        SwipeRefreshLayout.OnRefreshListener, ICheckpointsTripView, ICheckpointsTripQuestionView,
        View.OnClickListener {
    @Bean(CheckpointsTripServiceImpl.class)
    CheckpointsTripService checkpointsTripService;
    @Bean(CheckpointsTripQuestionServiceImpl.class)
    CheckpointsTripQuestionService checkpointsTripQuestionService;
    @ViewById
    SwipeRefreshLayout swipeRefreshLayout;

    @ViewById
    TextView headTitleText;

    @ViewById
    ItemCheckpointsTripView itemCheckpointsTripView1,
            itemCheckpointsTripView2,
            itemCheckpointsTripView3,
            itemCheckpointsTripView4,
            itemCheckpointsTripView5,
            itemCheckpointsTripView6,
            itemCheckpointsTripView7,
            itemCheckpointsTripView8,
            itemCheckpointsTripView9,
            itemCheckpointsTripView10;

    int nextStep;

    ItemCheckpointsTripView[] itemCheckpointsTripViews;

    PaperAnswerCacheDao paperAnswerCacheDao;

    String localDataQuestions;

    JSONObject currJsonObject;
    /**
     * 考试标题
     */
    String examTitle;

    @AfterViews
    public void initView() {
        String title = "进阶闯关";
        headTitleText.setText(title);
        checkpointsTripService.init(this);
        checkpointsTripQuestionService.init(this);
        itemCheckpointsTripViews = new ItemCheckpointsTripView[]{
                itemCheckpointsTripView1, itemCheckpointsTripView2, itemCheckpointsTripView3
                , itemCheckpointsTripView4, itemCheckpointsTripView5, itemCheckpointsTripView6, itemCheckpointsTripView7, itemCheckpointsTripView8
                , itemCheckpointsTripView9, itemCheckpointsTripView10
        };
        itemCheckpointsTripView1.setTextValue("初出茅庐");
        itemCheckpointsTripView2.setTextValue("新手上路");
        itemCheckpointsTripView3.setTextValue("小试牛刀");
        itemCheckpointsTripView4.setTextValue("运用自如");
        itemCheckpointsTripView5.setTextValue("得心应手");
        itemCheckpointsTripView6.setTextValue("驾轻就熟");
        itemCheckpointsTripView7.setTextValue("飘移高手");
        itemCheckpointsTripView8.setTextValue("风驰电掣");
        itemCheckpointsTripView9.setTextValue("人车合一");
        itemCheckpointsTripView10.setTextValue("炉火纯青");
        swipeRefreshLayout.setOnRefreshListener(this);
        paperAnswerCacheDao = new PaperAnswerCacheDao(getBaseActivity());

        onRefresh();
//        swipeRefreshLayout.postDelayed(new Runnable() {
//
//            @Override
//            public void run() {
//                if (isResponseResult()) {
//                    swipeRefreshLayout.setRefreshing(true);
//                    onRefresh();
//                }
//
//            }
//        }, 500);

    }

    public HomeActivity getHomeActivity() {
        return (HomeActivity) getActivity();
    }

    @Override
    public void onRefresh() {
        List<String> returnData = paperAnswerCacheDao.findQuestionsByStatus(6);
        if (returnData != null && returnData.size() > 1) {
            localDataQuestions = returnData.get(0);
        } else {
            localDataQuestions = null;
        }
        updateData(null);
        loadData();
    }


    public void loadData() {
        checkpointsTripService.getCheckpointsTripInfo();
    }


    @UiThread
    @Override
    public void getQuestionListSuccess(JSONObject jsonObject) {
        cancelOperatingProgressDialog();
        JSONObject paperJsonObject = TypeUtils.getJsonObject(jsonObject,
                "data", "paper");
        // 进入考试
        Intent intent = getBaseActivity().getIntent();
        intent.putExtra("examType", "6");
        intent.putExtra("paperId",
                TypeUtils.getJsonInteger(paperJsonObject, "id"));
        intent.putExtra("startTimeLong", System.currentTimeMillis());
        intent.putExtra("paperJsonObjectStr", paperJsonObject.toString());
        intent.putExtra("examTitle", examTitle);
        localDataQuestions = paperJsonObject.toString();
        updateData(currJsonObject);
        getHomeActivity().openOnlineExamFragment();
    }

    @UiThread
    @Override
    public void getQuestionListError(String error) {
        cancelOperatingProgressDialog();
        alertMessage(error);
    }

    @UiThread
    @Override
    public void checkpointsTripInfoSuccess(JSONObject jsonObject) {
        cancelLoadDataProgressDialog();
        currJsonObject = jsonObject;
        updateData(jsonObject);
    }

    @UiThread
    @Override
    public void checkpointsTripInfoError(String error) {
        cancelLoadDataProgressDialog();
        alertMessage(error);
    }


    /**
     * 刷新数据
     */
    public void updateData(JSONObject jsonObject) {
        /**
         * {
         "error_code": 0,
         "data": {
         "nextStep": 2,
         "stepsPassed": [
         {
         "step": 1,
         "paperId": 189
         }
         ]
         }
         }
         */

        JSONObject dataJsonObject = TypeUtils.getJsonObject(jsonObject, "data");
        nextStep = TypeUtils.getJsonInteger(dataJsonObject, "nextStep", 1);
        for (int i = 0; i < itemCheckpointsTripViews.length; i++) {
            ItemCheckpointsTripView itemCheckpointsTripView = itemCheckpointsTripViews[i];
            if (nextStep == 0) {
                itemCheckpointsTripView.setStatus(2);
            } else {
                if (nextStep - 1 == i) {
                    if (localDataQuestions != null) {
                        itemCheckpointsTripView.setStatus(0);
                    } else {
                        itemCheckpointsTripView.setStatus(4);
                    }
                } else if ((nextStep - 1) < i) {
                    itemCheckpointsTripView.setStatus(1);
                } else {
                    itemCheckpointsTripView.setStatus(2);
                }

            }
            itemCheckpointsTripView.setOnClickListener(this);
        }
    }


    @Override
    public void cancelLoadDataProgressDialog() {
        swipeRefreshLayout.setRefreshing(false);
    }

    @Override
    public void onClick(View v) {
        if (v instanceof ItemCheckpointsTripView) {
            ItemCheckpointsTripView itemCheckpointsTripView = (ItemCheckpointsTripView) v;
            examTitle = itemCheckpointsTripView.getTextValue();
            if (itemCheckpointsTripView.getStatus() == 0 || itemCheckpointsTripView.getStatus() == 4) {
                List<String> returnData = paperAnswerCacheDao.findQuestionsByStatus(6);

                long endTime = 0;
                if (returnData == null || returnData.size() < 1) {
                    localDataQuestions = null;
                } else {
                    localDataQuestions = returnData.get(0);
                    try {
                        endTime = Long.parseLong(returnData.get(1));
                    } catch (Exception ex) {
                        localDataQuestions = null;
                    }
                }
                if (localDataQuestions == null) {
                    checkpointsTripQuestionService.getQuestionList(nextStep);
                } else {

                    JSONObject paperJsonObject = JsonUtils.getJsonObject(localDataQuestions);
                    // 进入考试
                    Intent intent = getBaseActivity().getIntent();
                    intent.putExtra("examType", "6");
                    intent.putExtra("paperId",
                            TypeUtils.getJsonInteger(paperJsonObject, "id"));
                    //可以算出结束时间
                    long benginTime = System.currentTimeMillis();
//                    paperJsonObject.put("duration", (endTime - benginTime) / 1000);
                    intent.putExtra("startTimeLong", System.currentTimeMillis());
                    intent.putExtra("examTitle", examTitle);
                    intent.putExtra("paperJsonObjectStr", paperJsonObject.toString());
                    getHomeActivity().openOnlineExamFragment();
                }
            }
        }
    }


    @Override
    public void onDestroyView() {
        localDataQuestions = null;
        currJsonObject = null;
        currJsonObject = null;
        super.onDestroyView();
    }
}
